package com.module.app.pop

import android.content.Context
import android.widget.ProgressBar
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.module.app.ext.updateFlow
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.module.app.R
import com.module.frame.ext.observe
import java.math.BigDecimal

class ProgressPop2(context: Context, progressTitle: CharSequence) : BottomPopupView(context) {

    companion object {
        fun show(context: Context, progressTitle: CharSequence) {
            XPopup.Builder(context)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(true)
                .enableDrag(false)
                .asCustom(ProgressPop2(context, progressTitle))
                .show()
        }
    }

    private val progressBar: ProgressBar by lazy {
        rootView.findViewById(R.id.progress)
    }

    private val tvProgress: TextView by lazy {
        rootView.findViewById(R.id.tv_progress)
    }

    private val tvProgressTitle: TextView by lazy {
        rootView.findViewById(R.id.tv_progress_title)
    }

    private lateinit var bigDecimal: BigDecimal

    private var progressTitle: CharSequence = progressTitle;


    override fun getImplLayoutId(): Int {
        return R.layout.app_pop_progress2
    }

    override fun onCreate() {
        super.onCreate()
        tvProgressTitle.text = progressTitle
        observe(lifecycleScope, this, updateFlow) {
            when (it.status) {
                com.module.app.bean.IType.STATUS.end -> {
                    dismiss()
                }
                com.module.app.bean.IType.STATUS.progress -> {
                    progressBar.progress = it.progress.toInt()
                    bigDecimal = BigDecimal.valueOf(it.progress.toDouble())
                    tvProgress.text =
                        bigDecimal.setScale(0, BigDecimal.ROUND_DOWN).toPlainString() + "%"

                }
            }
        }
    }
}